package com.app.shortvideo.ui.viewmodel

import android.content.pm.PackageManager
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.MutableLiveData
import com.app.shortvideo.R
import com.app.shortvideo.VideoAdView
import com.app.shortvideo.ui.video.adapter.VideoListAdapter
import com.bytedance.sdk.openadsdk.api.banner.PAGBannerAd
import com.bytedance.sdk.openadsdk.api.banner.PAGBannerAdLoadListener
import com.bytedance.sdk.openadsdk.api.banner.PAGBannerRequest
import com.bytedance.sdk.openadsdk.api.banner.PAGBannerSize
import com.bytedance.sdk.openadsdk.api.nativeAd.PAGNativeAd
import com.bytedance.sdk.openadsdk.api.nativeAd.PAGNativeAdLoadListener
import com.bytedance.sdk.openadsdk.api.nativeAd.PAGNativeRequest
import com.bytedance.sdk.shortplay.api.PSSDK
import com.bytedance.sdk.shortplay.api.PSSDK.DetailPageConfig
import com.bytedance.sdk.shortplay.api.PSSDK.DrawAdProvider
import com.bytedance.sdk.shortplay.api.PSSDK.ShortPlayBlockResultListener
import com.bytedance.sdk.shortplay.api.PSSDK.ShortPlayDetailPageListener
import com.bytedance.sdk.shortplay.api.PSSDK.ShortPlayDetailPageListener.ItemType
import com.bytedance.sdk.shortplay.api.PSSDK.VideoPlayInfo
import com.bytedance.sdk.shortplay.api.ShortPlay
import com.bytedance.sdk.shortplay.api.ShortPlayFragment
import com.ss.ttvideoengine.Resolution


class VideoViewModel : BaseViewModel() {
    val videoResult = MutableLiveData<List<ShortPlay>>()
    lateinit var adapter: VideoListAdapter
    var feedAds: MutableList<PAGNativeAd> = ArrayList()
    private var detailFragment: ShortPlayFragment? = null
    private var bannerView: View? = null
    private var currentVideoPlayInfo: VideoPlayInfo? = null
    private var currentPlayingShortPlay: ShortPlay? = null
    private var currentPlayingIndex = 0

    fun initModelData(activity: FragmentActivity, shortPlay: ShortPlay) {
        // 预加载信息流广告
        loadPangleFeedAd()
        showDetailFragment(activity, shortPlay)
    }

    // 预加载信息流广告
    private fun showDetailFragment(activity: FragmentActivity, shortPlay: ShortPlay){
        val builder = DetailPageConfig.Builder()
        // 关闭底部预留视图区域，默认显示
//        builder.displayBottomExtraView(false);
        // 配置广告策略
        builder.adCustomProvider(object:PSSDK.AdCustomProvider{
            override fun getDetailDrawAdPositions(): MutableList<Int> {
                val integers = ArrayList<Int>()
                // 在第1集、第3集、第50集后面插入广告
                integers.add(1)
                integers.add(3)
                integers.add(50)
                return integers
            }

            override fun getDrawAdProvider(): DrawAdProvider {
                return object:DrawAdProvider{
                    override fun onPrepareAd() {
                        // 快划到广告插入位置时调用，可以在这里请求广告
                        loadPangleFeedAd()
                    }

                    override fun onObtainAdView(p0: Int, p1: Int): View {
                        // 返回广告View，如没有可用广告则返回null
                        return VideoAdView(activity,feedAds)
                    }

                    override fun onDestroy() {
                        // 播放页退出时调用，可在这里释放广告资源
                    }

                }
            }
        }).progressBarMarginToBottom(10)
        detailFragment = PSSDK.createDetailFragment(
            shortPlay,
            builder.build(),
            object : ShortPlayDetailPageListener {
                override fun onPlayFailed(errorInfo: PSSDK.ErrorInfo): Boolean {
                    // 视频播放失败
                    Log.d("TAG", "onPlayFailed() called with: errorInfo = [$errorInfo]")
                    if (errorInfo.code == PSSDK.ErrorInfo.ERROR_CODE_CURRENT_COUNTRY_NOT_SUPPORT) {
                        // 当前地区不支持播放，SDK会Toast提示，开发者也可以在此时显示弹窗等更友好的提示
                        val dialogBuilder: AlertDialog.Builder = AlertDialog.Builder(activity)
                        dialogBuilder.setMessage("当前地区不支持播放")
                        dialogBuilder.create().show()
                        // return true表示替换掉SDK内的Toast提示
                        return true
                    }
                    return false
                }

                override fun onShortPlayPlayed(shortPlay: ShortPlay, index: Int) {
                    currentPlayingShortPlay = shortPlay
                    currentPlayingIndex = index
                    // 每一集开始播放时回调，可用来记录播放历史
                    Log.d("TAG","onShortPlayPlayed() called with: shortPlay = [$shortPlay], index = [$index]")
                }

                override fun onItemSelected(position: Int, type: ItemType) {
                    Log.d("TAG","onItemSelected() called with: position = [$position], type = [$type]")
                    if (type == ItemType.AD) {
                        // 列表里是广告时，底部就不同时显示banner了，影响体验，换成普通view
                        val view: TextView = getAppLogoView(activity)
                        detailFragment?.setBottomExtraViewContent(view,ShortPlayFragment.BottomViewType.OTHER)
                    } else {
                        // 列表里是视频，可以显示底部banner
                        if (bannerView != null) {
                            detailFragment?.setBottomExtraViewContent(bannerView,ShortPlayFragment.BottomViewType.AD)
                        } else {
                            loadPangleBannerAd()
                        }
                    }
                }

                override fun onVideoPlayStateChanged(
                    shortPlay: ShortPlay,
                    index: Int,
                    playbackState: Int
                ) {
                    Log.d("TAG", "onVideoPlayStateChanged: playbackState=$playbackState")
                }

                override fun onVideoPlayCompleted(shortPlay: ShortPlay, index: Int) {
                    Log.d("TAG", "onVideoPlayCompleted: index=$index")
                }

                override fun onEnterImmersiveMode() {
                    // 进入沉浸式模式
                    Log.d("TAG", "onEnterImmersiveMode() called")
//                    immersiveMode = true
                }

                override fun onExitImmersiveMode() {
                    // 退出沉浸式模式
                    Log.d("TAG", "onExitImmersiveMode() called")
//                    immersiveMode = false
                }

                override fun isNeedBlock(shortPlay: ShortPlay, index: Int): Boolean {
                    // 询问index集是否锁定，true锁定后则该集无法自动播放，需要通过showAdIfNeed里完成解锁
                    // 默认对每一集均会询问，一旦返回false则此播放页不会再询问该集
                    Log.d(
                        "TAG",
                        "isNeedBlock() called with: shortPlay = [$shortPlay], index = [$index]"
                    )
                    return false
                }

                override fun showAdIfNeed(
                    shortPlay: ShortPlay,
                    index: Int,
                    listener: ShortPlayBlockResultListener
                ) {
                    // 当isNeedBlock指定index集锁定后，在用户切换到该集时，SDK不会播放视频，同时会调用此回调，可在此时展示激励广告或购买等交互，用户达成后调用listener.onShortPlayUnlocked告知SDK可播放该集
                    Log.d(
                        "TAG",
                        "showAdIfNeed() called with: shortPlay = [$shortPlay], index = [$index], listener = [$listener]"
                    )
//                    showUnLockDialog(shortPlay, index, listener)
                }

                override fun onVideoInfoFetched(
                    shortPlay: ShortPlay,
                    index: Int,
                    videoPlayInfo: VideoPlayInfo
                ) {
                    currentVideoPlayInfo = videoPlayInfo
                    // 每一集视频准备好时调用此方法告知本集的视频信息
                    val resolutions: Array<Resolution> = videoPlayInfo.supportResolutions
                    // 当前分辨率
                    val currentResolution: Resolution = videoPlayInfo.currentResolution
                    Log.d(
                        "TAG",
                        "onVideoInfoFetched: currentResolution=" + videoPlayInfo.currentResolution
                    )
                }
            })
        // 将播放页展示出来
        detailFragment?.let {
            activity.supportFragmentManager.beginTransaction().add(R.id.fragment_container,it).show(it).commit()
        }
        detailFragment?.startPlayIndex(currentPlayingIndex)
    }
    private fun getAppLogoView(activity: FragmentActivity): TextView {
        var applicationLabel: CharSequence = "TEST"
        try {
            applicationLabel = activity.packageManager.getApplicationLabel(activity.packageManager.getApplicationInfo(activity.packageName,0))
        } catch (e: PackageManager.NameNotFoundException) {
            Log.e("TAG", "getAppLogoView: ", e)
        }
        val view = TextView(activity)
        view.text = applicationLabel
        view.gravity = Gravity.CENTER
        return view
    }
    private fun loadPangleFeedAd() {
        val request = PAGNativeRequest()
        PAGNativeAd.loadAd("980088216", request, object : PAGNativeAdLoadListener {
            override fun onError(code: Int, message: String) {
                Log.d("AD", "load pangle ad fail, code=$code, message=$message")
            }

            override fun onAdLoaded(pagNativeAd: PAGNativeAd) {
                Log.d("AD", "load pangle ad success, $pagNativeAd")
                feedAds.add(pagNativeAd)
            }
        })
    }
    private fun loadPangleBannerAd() {
        val request = PAGBannerRequest(PAGBannerSize.BANNER_W_320_H_50)
        PAGBannerAd.loadAd("980099802", request, object : PAGBannerAdLoadListener {
            override fun onError(i: Int, s: String) {
                Log.d("TAG", "onError() called with: i = [$i], s = [$s]")
            }

            override fun onAdLoaded(pagBannerAd: PAGBannerAd) {
                Log.d("TAG", "onAdLoaded() called with: pagBannerAd = [$pagBannerAd]")
                bannerView = pagBannerAd.bannerView
                detailFragment!!.setBottomExtraViewContent(
                    bannerView,
                    ShortPlayFragment.BottomViewType.AD
                )
            }
        })
    }
}